package com.liuwang.meal.manager;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.liuwang.meal.bean.User;
import com.liuwang.meal.db.DBHelper;
import com.liuwang.meal.db.Users;

public class UserManager {
	private Context context = null;

	public UserManager(Context context) {
		this.context = context;
	}

	public void addUser(User user) {
		// 获取数据库
		DBHelper db = new DBHelper(this.context);
		SQLiteDatabase database = db.getWritableDatabase();
		String add = "insert into "+Users.TABLE+" (account,password,name,permission,remark) " + "values ('"
				+ user.getAccount() + "','" 
				+ user.getPassword() + "','" 
				+ user.getName() + "','" 
				+ user.getPermission() + "','"
				+ user.getRemark() + "')";
		// 执行语句
		database.execSQL(add);
		// 关闭数据库
		database.close();
	}
	
	// 根据用户名称密码查询
	public User query(String account,String password){
		// 获取数据库
		DBHelper db = new DBHelper(this.context);
		SQLiteDatabase database = db.getReadableDatabase();
		String sql = "select _id,account,password,name,permission,remark from "+Users.TABLE+" where account=? and password=?";
     	// 执行语句
    	Cursor  cursor = database.rawQuery(sql, new String[]{account,password});
    	
    	User user = null;
    	if(cursor.moveToFirst()){
    		Integer _id = cursor.getInt(0);
    		String name = cursor.getString(cursor.getColumnIndex("name"));
    		String permission = cursor.getString(cursor.getColumnIndex("permission"));
    		String remark = cursor.getString(cursor.getColumnIndex("remark"));
    	    user = new User(_id,account,password,name,permission,remark);	
    	}

    	// 关闭数据库
    	database.close();
    	return user;
	}
	
	// 查询所有用户
	public List<User> queryUsers(){
		// 获取数据库
		DBHelper db = new DBHelper(this.context);
		SQLiteDatabase database = db.getReadableDatabase();
		String sql = "select _id,account,password,name,permission,remark from "+Users.TABLE+" order by account";
     	// 执行语句
    	Cursor  cursor = database.rawQuery(sql,null);
    	// 循环遍历结果集
    	List<User>  list = new ArrayList<User>();

    	while(cursor.moveToNext()){
    		Integer _id = cursor.getInt(0);
    		String account = cursor.getString(cursor.getColumnIndex("account"));
    		String password = cursor.getString(cursor.getColumnIndex("password"));
    		String name = cursor.getString(cursor.getColumnIndex("name"));
    		Integer permission = cursor.getInt(cursor.getColumnIndex("permission"));
    		String remark = cursor.getString(cursor.getColumnIndex("remark"));
    		User user = new User(_id,account,password,name,permission.toString(),remark);
    	    list.add(user);
    	}

    	// 关闭数据库
    	database.close();
    	return list;
	}
}
